//
//  OASelectFileViewController.m
//  LongOA
//
//  Created by XuJiuming on 15/9/28.
//  Copyright (c) 2015年 梁文朗. All rights reserved.
//

#import "OASelectFileViewController.h"

@interface OASelectFileViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView* _tableView;
    NSArray* arrList;
}
@property(nonatomic,strong) NSString* currentInfo;
@end

@implementation OASelectFileViewController
- (void)leftBarClicked:(id)sender {
    //[self.navigationController popViewControllerAnimated:NO];
    NSString* temp= NSHomeDirectory();
    if ([self.currentInfo isEqualToString:temp]) {
        [self dismissViewControllerAnimated:NO completion:nil];
    } else {
        NSMutableArray* arrTemp=[[NSMutableArray alloc] init];
        NSFileManager *fm = [NSFileManager defaultManager];

        self.currentInfo=[self.currentInfo stringByDeletingLastPathComponent];
        NSArray *contentOfFolder = [fm contentsOfDirectoryAtPath:self.currentInfo error:NULL];
        for (NSString *aPath in contentOfFolder) {
            if (![aPath isEqualToString:@".com.apple.mobile_container_manager.metadata.plist"] && ![aPath isEqualToString:@".DS_Store"]) {
                [arrTemp addObject:aPath];
            }
        }
        if (arrTemp.count>0) {
            arrList=arrTemp;
        }
        [_tableView reloadData];
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createNavWithTitle:@"选择文件" createMenuItem:^UIView *(int nIndex)
     {
         float btnwidth=40.0f;
         float btnheight=40.0f;
         if (nIndex ==0)
         {
             UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
             [btn setFrame:CGRectMake(10.0f, 20.0f+(self.navView.height-20 - 40)/2, btnwidth, btnheight)];
             [btn setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
             [btn addTarget:self action:@selector(leftBarClicked:) forControlEvents:UIControlEventTouchUpInside];
             btn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
             return btn;
         }
        return nil;
     }];
    /*
     // 获取沙盒主目录路径
     NSString *homeDir = NSHomeDirectory();
     // 获取Documents目录路径
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSString *docDir = [paths objectAtIndex:0];
     // 获取Caches目录路径
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
     NSString *cachesDir = [paths objectAtIndex:0];
     // 获取tmp目录路径
     NSString *tmpDir =  NSTemporaryDirectory();
     */
    //NSString *path=nil;
    //NSDirectoryEnumerator *dirEnum;
    NSMutableArray* arrTemp=[[NSMutableArray alloc] init];
    NSFileManager *fm = [NSFileManager defaultManager];
    
    self.currentInfo = NSHomeDirectory();
    NSArray *contentOfFolder = [fm contentsOfDirectoryAtPath:self.currentInfo error:NULL];
    for (NSString *aPath in contentOfFolder) {
        //获取当前的工作目录的路径
        //path = [self.currentInfo stringByAppendingPathComponent:aPath];
        //NSLog(@"%@",[path lastPathComponent]);
        if (![aPath isEqualToString:@".com.apple.mobile_container_manager.metadata.plist"] && ![aPath isEqualToString:@".DS_Store"]) {
            [arrTemp addObject:aPath];
        }
        /*
        //遍历这个目录的第一种方法：（深度遍历，会递归枚举它的内容）
        dirEnum = [fm enumeratorAtPath:path];
        //NSLog(@"1.Contents of %@:",path);
        while ((path = [dirEnum nextObject]) != nil)
        {
            //NSLog(@"%@",path);
            NSString *temp2=[[temp1 stringByAppendingPathComponent:aPath] stringByAppendingPathComponent:path];
            
            BOOL isDir = NO;
            if ([fm fileExistsAtPath:temp2 isDirectory:&isDir])
            {
                if (isDir == YES) {
                } else {
                    
                }
            }
        }*/
    }
    if (arrTemp.count>0) {
        arrList=arrTemp;
    }
    
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0.0, self.navView.bottom, SCREEN_WIDTH, SCREEN_HEIGHT-self.navView.bottom) style:UITableViewStylePlain];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.backgroundColor=[UIColor clearColor];
    _tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:_tableView];
    _tableView.showsVerticalScrollIndicator=NO;
    [self setExtraCellLineHidden:_tableView];
}
-(void)setExtraCellLineHidden: (UITableView *)tableView {
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    [tableView setTableHeaderView:view];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark TableView delegate
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //8.0的分割线额外设置
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 8.0) {
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsZero];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
        
        if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)])
            [cell setPreservesSuperviewLayoutMargins:NO];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [arrList count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44.0;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"newCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        cell.backgroundColor=[UIColor clearColor];
        cell.contentView.backgroundColor=[UIColor clearColor];
        cell.textLabel.font=[UIFont systemFontOfSize:14.0];
        
    }
    cell.imageView.image=[UIImage imageNamed:@"icon_folder_small"];
    cell.textLabel.text=[arrList objectAtIndex:indexPath.row];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString* strTemp=[arrList objectAtIndex:indexPath.row];
    NSString *temp2=[self.currentInfo stringByAppendingPathComponent:strTemp];
    
    BOOL isDir = NO;
    if ([fm fileExistsAtPath:temp2 isDirectory:&isDir])
    {
        if (isDir == YES) {
            NSMutableArray* arrTemp=[[NSMutableArray alloc] init];
            
            self.currentInfo=[self.currentInfo stringByAppendingPathComponent:strTemp];
            NSArray *contentOfFolder = [fm contentsOfDirectoryAtPath:self.currentInfo error:NULL];
            for (NSString *aPath in contentOfFolder) {
                if (![aPath isEqualToString:@".com.apple.mobile_container_manager.metadata.plist"] && ![aPath isEqualToString:@".DS_Store"]) {
                    [arrTemp addObject:aPath];
                }
            }
            if (arrTemp.count>0) {
                arrList=arrTemp;
            }
            [_tableView reloadData];
        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ADDPATHPIC" object:temp2];
            [self dismissViewControllerAnimated:NO completion:nil];
        }
    }
}
@end
